'use client';

import React, { useState, useEffect } from 'react';
import { Typography, Button, Space, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useRouter } from 'next/navigation';
import TicketList from '@/components/TicketList';
import TicketFilters from '@/components/TicketFilters';
import { addAuthHeader } from '@/utils/auth';
import { Ticket, TicketFilters as TicketFiltersType, PaginatedResponse, ApiResponse } from '@/types/ticket';

const { Title } = Typography;

const HomePage: React.FC = () => {
  const router = useRouter();
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [filters, setFilters] = useState<TicketFiltersType>({});

  // 获取工单列表
  const fetchTickets = async (page = 1, pageSize = 10, currentFilters = filters) => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString(),
      });

      // 添加过滤参数
      if (currentFilters.status?.length) {
        params.append('status', currentFilters.status.join(','));
      }
      if (currentFilters.priority?.length) {
        params.append('priority', currentFilters.priority.join(','));
      }
      if (currentFilters.category?.length) {
        params.append('category', currentFilters.category.join(','));
      }
      if (currentFilters.assignee?.length) {
        params.append('assignee', currentFilters.assignee.join(','));
      }
      if (currentFilters.search) {
        params.append('search', currentFilters.search);
      }

      const response = await fetch(`/api/tickets?${params}`, {
        headers: addAuthHeader(),
      });
      const result: ApiResponse<PaginatedResponse<Ticket>> = await response.json();

      if (result.success) {
        setTickets(result.data.data);
        setPagination({
          current: result.data.page,
          pageSize: result.data.pageSize,
          total: result.data.total,
        });
      } else {
        message.error(result.message || '获取工单列表失败');
      }
    } catch (error) {
      console.error('获取工单列表失败:', error);
      message.error('获取工单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理过滤器变化
  const handleFiltersChange = (newFilters: TicketFiltersType) => {
    setFilters(newFilters);
    fetchTickets(1, pagination.pageSize, newFilters);
  };

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    fetchTickets(page, pageSize);
  };

  // 创建新工单
  const handleCreateTicket = () => {
    router.push('/tickets/create');
  };

  // 查看工单详情
  const handleViewTicket = (ticket: Ticket) => {
    router.push(`/tickets/${ticket.id}`);
  };

  // 删除工单
  const handleDeleteTicket = async (ticketId: string) => {
    try {
      const response = await fetch(`/api/tickets/${ticketId}`, {
        method: 'DELETE',
        headers: addAuthHeader(),
      });
      const result: ApiResponse<null> = await response.json();

      if (result.success) {
        message.success('工单删除成功');
        fetchTickets(pagination.current, pagination.pageSize);
      } else {
        message.error(result.message || '删除工单失败');
      }
    } catch (error) {
      console.error('删除工单失败:', error);
      message.error('删除工单失败');
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchTickets();
  }, []);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={3} style={{ margin: 0 }}>
          工单列表
        </Title>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleCreateTicket}
          size="large"
        >
          创建工单
        </Button>
      </div>

      <TicketFilters
        filters={filters}
        onFiltersChange={handleFiltersChange}
        loading={loading}
      />

      <TicketList
        tickets={tickets}
        loading={loading}
        pagination={pagination}
        onPaginationChange={handlePaginationChange}
        onViewTicket={handleViewTicket}
        onDeleteTicket={handleDeleteTicket}
      />
    </div>
  );
};

export default HomePage; 